/**
 * 
 */
package photosalvage.entity;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javax.persistence.TypedQuery;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;

import photosalvage.util.JPAUtils;


/**
 * @author shumpei
 *
 */
public class UserRepository extends BaseRepository<User, Long> {

	public User findByCredentials(String email, String password) {
		String passwordHash = makeHash(password);
		TypedQuery<User> q =
			getEntityManager().createQuery(
					"select u from User u where u.email = :email and u.password = :password", User.class);
		q.setParameter("email", email);
		q.setParameter("password", passwordHash);
		
		return JPAUtils.getSingleOrNull(q);
	}
	
	public User findByEmail(String email) {
		TypedQuery<User> q =
			getEntityManager().createQuery(
					"select u from User u where u.email = :email", User.class);
		q.setParameter("email", email);
		
		return JPAUtils.getSingleOrNull(q);
	}
	public User create(UserDto param) {
		User user = new User();
		user.setEmail(param.email);
		user.setName(param.name);
		user.setPassword(makeHash(param.password));
		user.setAdministrator(param.administrator);
		persist(user);
		return user;
	}
	
	public User update(UserDto param) {
		if (param.id == null) {
			throw new IllegalArgumentException("user id is null");
		}
		User user = find(param.id);
		if (user == null) {
			throw new IllegalArgumentException("user not found.id=" + param.id);
		}
		user.setEmail(param.email);
		user.setName(param.name);
		if (StringUtils.isNotEmpty(param.password)) {
			user.setPassword(makeHash(param.password));
		}
		user.setAdministrator(param.administrator);
		merge(user);
		return user;
	}
	
	private String makeHash(String s) {
		MessageDigest md;
		try {
			md = MessageDigest.getInstance("MD5");
		} catch (NoSuchAlgorithmException e) {
			throw new RuntimeException(e);
		}
		byte[] binary = md.digest(s.getBytes());
		return Base64.encodeBase64String(binary);
	}
}
